import crypto from "crypto";
import {getUploadToken} from "@/api/system/common";
import * as qiniu from "qiniu-js";

const MAX_FILE_SIZE = 5 * 1024 * 1024; // 限制文件大小为 5MB

/**
 *七牛云上传单个文件
 * @param prefix 文件夹  xx/xx/xx/
 * @param file 文件
 * @param next 上传进度回调
 */
export function qinUpload(prefix,file,next) {

    // console.log(file);
    return new Promise(async (resolve, reject) => {

        //校验文件大小
        if (file.size > MAX_FILE_SIZE) {
            this.$notify({
                title: '提示',
                message: "文件超过允许的大小限制",
                type:"info"
            });
            reject("文件超过允许的大小限制");
            return;
        }
        //获取上传token信息
        const res = await getUploadToken();

        const {token,url,region} = res.data;

        // console.log(res)

        //生成文件md5
        let md5 = await computeFileMD5(file);

        //获取文件扩展名
        let extension = file.name.split('.').pop();

        //拼接最终上传路径
        const name = prefix + md5 + '.' + extension;

        //上传配置
        const config = {
            useCdnDomain: true,
            region: region
        };

        //开始上传
        const observable = qiniu.upload(file, name, token, config)

        //监听上传
        observable.subscribe(
            {
                next(res) {
                    // ...
                    next(res)
                },
                error: (err) => {
                    // ...
                    reject(err)
                },
                complete: (res) => {

                    resolve(url + '/' + res.key)
                }
            }
        ) //

    })

}

// 计算文件的 MD5 值
async function computeFileMD5(file) {
    const buffer = await readFileAsBuffer(file);
    const hash = crypto.createHash("md5");
    hash.update(buffer);
    return hash.digest("hex");
}

// 将文件读取为 Buffer
async function readFileAsBuffer(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
            resolve(Buffer.from(reader.result));
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
    });
}


